package com.itcast.rpc.core.client.handler;

import com.itcast.rpc.core.base.RpcResponse;
import com.itcast.rpc.core.client.response.RpcFutureResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-23 10:54
 **/
public class ClientRpcHandler extends SimpleChannelInboundHandler<RpcResponse> {
    private static final Logger LOGGER =
            LoggerFactory.getLogger(ClientRpcHandler.class);
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error("客户端出错-" + cause);
        ctx.close();
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                                RpcResponse msg) throws Exception {
        LOGGER.info("接收到服务端的消息： requestId = " + msg.getRequestId());
        
        //
        //接收到服务端的消息后，通知响应已经完成
        // 通过RpcFutureResponse中的Map获取到RpcFutureResponse对象，进⾏⽅法回调
        RpcFutureResponse rpcFutureResponse =
                RpcFutureResponse.getRpcFutureResponse(msg.getRequestId());
        if (null != rpcFutureResponse) {
            rpcFutureResponse.setResponse(msg);
        } else {
            LOGGER.warn("没有找到对应的RpcFutureResponse对象~ requestId = " +
                    msg.getRequestId());
        }
    }
}
